<!-- 场景模板列表页 -->
<template>
  <MenuPage 
      :data="dataList" 
      :columns="columns" 
      :total="totalCount" 
      :page.sync="query.pageIndex" 
      :size.sync="query.pageSize"
      :loading="loading"
      @queryFun="getSceneTemplateList">
    <template slot="search">
      <Button ghost type="primary" @click="showAddOrUpdate('')">
        <Icon type="ios-cloud-upload-outline"></Icon>
        导入场景模板
      </Button>
      <!-- <Upload ref="upload"
                          :action="upload.uploadAction"
                          :show-upload-list="false"
                          :format="upload.format"
                          :on-format-error="handleFormatError"
                          :on-success="handleSuccessUpload"
                          :before-upload="handleBeforeUpload"
                          :headers="upload.uploadHeader">
                  <Button ghost type="primary" :disabled="upload.uploadList.length > 0">
                      <div v-if="upload.uploadList.length == 0">
                          <Icon type="ios-cloud-upload-outline"></Icon>
                          <span>导入场景模板</span>
                          <Tooltip content="请选择json格式文件导入"><Icon type="ios-alert" style="color:#f90" size="16"></Icon></Tooltip>
                      </div>
                      <div class="demo-upload-list" v-for="item in upload.uploadList">
                          <Progress v-if="item.showProgress" :percent="item.percentage" hide-info style="width:100px"></Progress>
                      </div>
                  </Button>
              </Upload> -->
      <Divider type="vertical" />
      <Checkbox v-model="createByMe" @on-change="debounceSearch">我创建的</Checkbox>
      <Select filterable clearable placeholder="类型" v-model="query.type" filterable style="width:150px;margin-left:15px;"
        @on-change="changePage(1)">
        <Option :value="type.value" v-for="type in sceneTypeArr" :key="type.value">{{
          type.label
          }}</Option>
      </Select>
      <Select filterable clearable placeholder="可见性" v-model="query.visibility" filterable style="width:150px;margin-left:15px;"
        @on-change="changePage(1)">
        <Option value="share">共享</Option>
        <Option value="private">私有</Option>
        <!--<Option value="public">公共</Option>-->
      </Select>
      <Input v-model.trim="query.name" clearable placeholder="名称" style="width:180px;margin-left:15px;"
        @on-change="debounceSearch" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshList()">
        <Icon size="16" type="ios-refresh" />
      </Button>
    </template>
      <!-- 修改模板 -->
      <EditModal v-model="editModal.show" :type="editModal.type" :data="editModal.data"
        @ok="editModal.type === 'import' ? refreshList() : getSceneTemplateList()"></EditModal>
  </MenuPage>
</template>
<script>
  import encryption from '@/libs/encryption.js';
  import { debounce } from '@/libs/utils';
  import {
    getSceneTemplateList,
    deleteSceneTemplate,
    exportSceneTemplate
  } from '@/api/drill_compete.js';
  import EditModal from './edit.vue';
  import pageTitle from '@/mixin/pageTitle';
  export default {
    name: 'SceneTemplate',
    mixins: [pageTitle],
    components: {  EditModal },
    prop: {
      type: {
        //选择使用 || 管理
        type: String,
        default: 'manage'
      }
    },
    data() {
      let September = sessionStorage.getItem('November');
      September = JSON.parse(encryption.SelfUseDecrypt(September));
      return {
        USER_ID: September.userId,
        isRootDesigner: September.isRootDesigner,
        dataList: [], //模板列表
        totalCount: 0,
        loading: false,
        query: {
          pageIndex: 1,
          pageSize: 10,
          name: '',
          type: '',
          visibility: ''
        },
        createByMe: false,
        editModal: {
          show: false,
          data: {},
          type: 'import'
        },
        upload: {
          uploadAction: '/api/compete/sceneTemplate/importSceneTemplate',
          uploadHeader: {
            Authorization: localStorage.token,
            Accept: '*/*'
          },
          format: ['json'],
          uploadList: []
        },
        columns: [
          {
            title: '模板名称',
            key: 'name',
            tooltip: true,
            placement: 'top-left',
            minWidth: 100
          },
          {
            title: '类型',
            key: 'type',
            minWidth: 100,
            render: (h, params) => {
              return h('span', this.setType(params.row.type));
            }
          },
          {
            title: '可见性',
            key: 'visibility',
            minWidth: 100,
            render: (h, params) => {
              return h(
                'span',
                { style: { color: this.setVisibility(params.row.visibility).color } },
                this.setVisibility(params.row.visibility).text
              );
            }
          },
          {
            title: '描述',
            key: 'description',
            minWidth: 100,
          },
          {
            title: '创建者',
            key: 'creatorName',
            minWidth: 100,
          },
          {
            title: '创建时间',
            key: 'createTime',
            minWidth: 100,
          },
          {
            title: '操作',
            key: 'action',
            width: 160,
            align: 'left',
            ellipsis: true,
            placement: 'top-right',
            order: 2,
            opList:[
              {
                txt:'修改',
                type:'modify',
                disabled: this.setReBtnStatus,
                fun:this.showAddOrUpdate
              },
              {
                txt:'导出',
                type:'download',
                fun:this.exportTemplate
              },
              {
                txt:'删除',
                title: '确定要删除这个模板吗?',
                type:'delete',
                tooltip:true,
                disabled: this.setReBtnStatus,
                fun:(data) => this.deleteSceneTemplate(data.id)
              },
            ],
            // render: (h, params) => {
            //   return h('div', [
            //     h(
            //       'Button',
            //       {
            //         props: {
            //           type: 'text',
            //           size: 'small',
            //           disabled: this.setReBtnStatus(params.row)
            //         },
            //         attrs: {
            //           title: '修改'
            //         },
            //         style: {
            //           background: 'none',
            //           border: 'none',
            //           boxShadow: 'none'
            //         },
            //         on: {
            //           click: () => {
            //             this.showAddOrUpdate(params.row);
            //           }
            //         }
            //       },
            //       [
            //         h('img', {
            //           attrs: {
            //             src: !this.setReBtnStatus(params.row)
            //               ? require('../../../../assets/project/modifys-h.png')
            //               : require('../../../../assets/project/modifys.png')
            //           },
            //           style: {
            //             cursor: 'pointer',
            //             'margin-right': '5px',
            //             'vertical-align': 'middle',
            //             display: 'inline-block',
            //             marginBottom: '4px'
            //           }
            //         })
            //       ]
            //     ),
            //     h(
            //       'Button',
            //       {
            //         props: {
            //           type: 'text',
            //           size: 'small'
            //         },
            //         attrs: {
            //           title: '导出'
            //         },
            //         style: {
            //           background: 'none',
            //           border: 'none',
            //           boxShadow: 'none'
            //         },
            //         on: {
            //           click: () => {
            //             this.exportTemplate(params.row);
            //           }
            //         }
            //       },
            //       [
            //         h('img', {
            //           attrs: {
            //             src: require('../../../../assets/project/download-h.png')
            //           },
            //           style: {
            //             cursor: 'pointer',
            //             'margin-right': '5px',
            //             'vertical-align': 'middle',
            //             display: 'inline-block',
            //             marginBottom: '4px'
            //           }
            //         })
            //       ]
            //     ),
            //     h(
            //       'Poptip',
            //       {
            //         props: {
            //           confirm: true,
            //           'ok-text': '确定',
            //           'cancel-text': '取消',
            //           type: 'error',
            //           size: 'large',
            //           title: '确定要删除这个模板吗?',
            //           transfer: true
            //         },
            //         style: {
            //           marginLeft: '0px'
            //         },
            //         on: {
            //           'on-ok': () => {
            //             this.deleteSceneTemplate(params.row.id);
            //           }
            //         }
            //       },
            //       [
            //         h(
            //           'Button',
            //           {
            //             props: {
            //               type: 'text',
            //               size: 'small',
            //               disabled: this.setReBtnStatus(params.row)
            //             },
            //             attrs: {
            //               title: '删除'
            //             },
            //             style: {
            //               //              marginRight: '5px',
            //               background: 'none',
            //               border: 'none',
            //               boxShadow: 'none'
            //             }
            //           },
            //           [
            //             h('img', {
            //               attrs: {
            //                 src: !this.setReBtnStatus(params.row)
            //                   ? require('../../../../assets/project/delNote-h.png')
            //                   : require('../../../../assets/project/delNote-d.png')
            //               },
            //               style: {
            //                 cursor: 'pointer',
            //                 'margin-right': '5px',
            //                 'vertical-align': 'middle',
            //                 display: 'inline-block',
            //                 marginBottom: '4px'
            //               }
            //             }),
            //             h('span', {
            //               style: {
            //                 cursor: 'pointer',
            //                 color: !this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
            //               }
            //             })
            //           ]
            //         )
            //       ]
            //     )
            //   ]);
            // }
          }
        ],
        sceneTypeArr: [
          {
            value: 0,
            label: '对抗演练'
          },
          // {
          //     value:1,
          //     label:'攻防赛'
          // },
          // {
          //     value:2,
          //     label:'夺旗赛'
          // },
          // {
          //     value:3,
          //     label:'知识赛'
          // },
          {
            value: 4,
            label: '渗透演练'
          },
          // {
          //     value:5,
          //     label:'护网演练'
          // },
          {
            value: 7,
            label: '综合演练'
          },
          {
            value: 10,
            label: '应急防御演练'
          }
          // {
          //     value:8,
          //     label:'攻防赛Plus'
          // },
          // {
          //     value:9,
          //     label:'运维赛'
          // }
        ]
      };
    },
    mounted() {
      this._query = { ...this.query };
      // this.setStyle(); // 计算分页大小后，获取场景列表
      // window.addEventListener('resize', this.setStyle);
      this.getSceneTemplateList();
    },
    methods: {
      // 通过屏幕可显示高度，计算能展示多少条记录，最少需要展示一条
      setStyle() {
        clearTimeout(this.refreshTimer);
        this.refreshTimer = setTimeout(() => {
          window.fullHeight = document.documentElement.clientHeight;
          window.fullWidth = document.documentElement.clientWidth;
          this.fullHeight = window.fullHeight;
          this.fullWidth = window.fullWidth;
          this.setTableHei = this.fullHeight - 197;
          // this.query.pageSize = Math.floor(this.setTableHei / 96) || 1;
          this.query.pageIndex = 1;
          this.getSceneTemplateList();
        }, 200);
      },
      getSceneTemplateList() {
        this.loading = true;
        let query = { ...this.query };
        if (this.createByMe) {
          query.creator = this.USER_ID;
        }
        getSceneTemplateList(query)
          .then(({ code, data, message }) => {
            if (code == 1) {
              this.dataList = data.items;
              this.totalCount = data.total;
            } else {
              this.$Message.error(message);
            }
            this.loading = false;
          })
          .catch((error) => {
            this.loading = true;
            console.log(error);
          });
      },
      changePage(page) {
        this.query.pageIndex = page;
        this.getSceneTemplateList();
      },
      debounceSearch: debounce(function () {
        this.changePage(1);
      }, 500),
      refreshList() {
        this.createByMe = false;
        this.query = { ...this._query, pageSize: this.query.pageSize };
        this.getSceneTemplateList();
      },
      handleFormatError() {
        this.upload.uploadList = [];
        this.$Message.warning('文件格式错误');
      },
      handleBeforeUpload() {
        this.upload.uploadList = this.$refs.upload.fileList;
        return true;
      },
      handleSuccessUpload(res) {
        this.upload.uploadList = [];
        if (res.code == 1) {
          this.$Message.info('导入成功');
          this.refreshList();
        } else {
          this.$Message.warning(res.message);
        }
      },
      exportTemplate(obj) {
        const msg = this.$Message.loading({
          content: '正在导出...',
          duration: 0
        });
        let { id, name } = obj;
        exportSceneTemplate(id)
          .then((data) => {
            setTimeout(msg, 100);
            if (!data.code) {
              const downloadElement = document.createElement('a');
              const href = window.URL.createObjectURL(data);
              downloadElement.href = href;
              downloadElement.download = `${name}.json`;
              document.body.appendChild(downloadElement);
              downloadElement.click();
              document.body.removeChild(downloadElement); // 下载完成移除元素
              window.URL.revokeObjectURL(href); // 释放掉blob对象
            } else {
              this.$Message.error('导出失败');
            }
          })
          .catch((error) => {
            setTimeout(msg, 100);
            this.$Message.error('导出失败');
          });
      },
      // 显示修改modal
      showAddOrUpdate(data) {
        this.editModal.type = data ? 'update' : 'import';
        this.editModal.show = true;
        this.editModal.data = data;
      },
      deleteSceneTemplate(id) {
        deleteSceneTemplate(id)
          .then(({ code, data, message }) => {
            if (code == 1) {
              this.$Message.info('删除成功');
              if (this.query.pageIndex > 1 && this.totalCount == 1) {
                this.query.pageIndex--;
              }
              this.getSceneTemplateList();
            } else {
              this.$Message.error(message);
            }
          })
          .catch((e) => {
            this.$Message.error(message);
          });
      },
      // 按钮点击状态
      setReBtnStatus(params) {
        let userid = params.creator;
        if ((userid === this.USER_ID || this.isRootDesigner) && params.visibility != 'public') {
          return false;
        } else {
          return true;
        }
      },
      setType(val) {
        let type = this.sceneTypeArr.find((type) => type.value == val);
        return type ? type.label : '';
      },
      // 设置可见性
      setVisibility(val) {
        let obj = {};
        let text = '';
        let color = '';
        if (val === 1 || val === '1' || val === 'share') {
          text = '共享';
          color = '#32CD32';
        } else if (val === 0 || val === '0' || val === 'private') {
          text = '私有';
          color = '#FFA500';
        } else if (val === 2 || val === '2' || val === 'public') {
          text = '公共';
          color = '#4169E1';
        }
        obj.text = text;
        obj.color = color;
        return obj;
      }
    }
  };
</script>
<style scoped>
</style>